// 我的试卷页面
<template>
    <div id="myExam">
        <div class="wrapper">
            <ul class="top">
                <li class="order"><i class="el-icon-a-041" style="font-size: 20px;"> 试卷列表</i></li>
                <li class="search-li">
                    <div class="icon">
                        <input
                            type="text"
                            placeholder="试卷名称"
                            class="search"
                            v-model="key"
                        /><i class="el-icon-search"></i>
                    </div>
                </li>
                <li>
                    <el-button type="primary" @click="search()" icon="el-icon-a-042"
                        >搜索试卷</el-button
                    >
                </li>
            </ul>
            <ul class="paper" v-loading="loading">
                <li
                    @click="toExamMsg(item)"
                    class="item"
                     v-for="(item, index) in reversedRecords"
                    :key="index"
                >
                    <h4>{{ item.subject }}-{{ item.type }}</h4>

                    <div class="info">
                        <i class="el-icon-time"></i
                        ><span>{{ item.startTime.substr(0, 10) }}</span>
                        <i class="iconfont icon-icon-time"></i
                        ><span v-if="item.totalTime != null"
                            >限时{{ item.totalTime }}分钟</span
                        >
                        <i class="iconfont icon-fenshu"></i
                        ><span>满分{{ item.totalScore }}分</span>
                    </div>
                </li>
            </ul>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagination.current"
                    :page-sizes="[6, 10, 20, 40]"
                    :page-size="pagination.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"
                >
                </el-pagination>
            </div>
        </div>
    </div>
</template><script>
export default {
  data() {
    return {
      loading: false,
      key: null,
      pagination: {
        current: 1,
        total: null,
        size: 6,
        records: []
      },
      // ✅ 新增：缓存 paperConfig，避免重复请求
      paperConfigCache: new Map() // key: paperId, value: config
    };
  },
  created() {
    this.getExamInfo();
    this.loading = true;
  },
  computed: {
    reversedRecords() {
        // 使用 slice() 创建副本，避免修改原始数组
        return this.pagination.records.slice().reverse();
    }
},
  methods: {
    getExamInfo() {
      this.loading = true;
      this.$axios
        .get('/api/exams', {
          params: {
            page: this.pagination.current,
            size: this.pagination.size,
            key: this.key
          }
        })
        .then((res) => {
          if (res.data.code === 200) {
            const data = res.data.data;
            if (Array.isArray(data)) {
              this.pagination.total = data.length;
              this.pagination.records = data;
            } else if (data && data.records !== undefined) {
              this.pagination = data;
            } else {
              this.pagination.total = 0;
              this.pagination.records = [];
            }
          } else {
            this.$message.error(res.data.message || '请求失败');
            this.pagination.total = 0;
            this.pagination.records = [];
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('网络错误，加载失败');
        });
    },
    handleSizeChange(val) {
      this.pagination.size = val;
      this.getExamInfo();
    },
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.getExamInfo();
    },
    search() {
      // ✅ 修复：复用 getExamInfo，走分页 + 后端搜索
      this.pagination.current = 1;
      this.getExamInfo();
    },

    // ✅ 核心方法：进入考试（带 loading、缓存、时间校验）
    async toExamMsg(exam) {
      const userId = this.$cookies.get("cid");
      if (!userId) {
        this.$message.error('请先登录');
        return;
      }

      // ✅ 检查考试是否开始
      if (exam.examDate > this.formatDateNow()) {
        this.$message.error("考试尚未开始，请等待");
        return;
      }

      // ✅ 检查考试是否已结束
      if (exam.endDate && exam.endDate < this.formatDateNow()) {
        this.$message.error("考试已结束，无法进入");
        return;
      }

      let paperId = exam.paperId;


      try {
  this.loading = true;

  const templatePaperId = exam.paperId;      // 原始试卷模板 ID
  const cid = this.$cookies.get('cid');

  // ✅ 1. 构造唯一 userPaperId
  const userPaperId = `${templatePaperId}`;

  // ✅ 2. 检查该用户是否已有试卷（使用 userPaperId）
  const hasPaperRes = await this.$axios.get('/api/paperManage/exists', {
    params: { 
      paperId: userPaperId,  // ✅ 使用唯一 ID
      userId
    }
  });

  const hasPaper = hasPaperRes.data.data === true;

  if (hasPaper) {
    this.$message.success('继续上次的考试');
    this.$router.push({
      path: '/examMsg',
      query: { examCode: exam.examCode, paperId: userPaperId }  // ✅ 把 userPaperId 传下去
    });
    return;
  }

  // ✅ 3. 获取组卷配置（缓存仍可用，基于 templatePaperId）
  let config = this.paperConfigCache.get(templatePaperId);
  if (!config) {
    const configRes = await this.$axios.get('/api/paperConfig', {
      params: { paperId: templatePaperId }  // ✅ 用模板 ID 获取配置
    });
    if (configRes.data.code !== 200) {
      this.$message.error('试卷配置加载失败');
      return;
    }
    config = configRes.data.data;
    this.paperConfigCache.set(templatePaperId, config);
  }

  // ✅ 4. 并发抽题（无需改）
  const [multiRes, fillRes, judgeRes] = await Promise.all([
    this.$axios.get('/api/multiQuestion/batch', {
      params: { count: config.multipleCount, subject: config.bankSubject }
    }),
    this.$axios.get('/api/fillQuestion/batch', {
      params: { count: config.fillCount, subject: config.bankSubject }
    }),
    this.$axios.get('/api/judgeQuestion/batch', {
      params: { count: config.judgeCount, subject: config.bankSubject }
    })
  ]);

  const multiQuestions = multiRes.data.data || [];
  const fillQuestions = fillRes.data.data || [];
  const judgeQuestions = judgeRes.data.data || [];

  if (
    multiQuestions.length < config.multipleCount ||
    fillQuestions.length < config.fillCount ||
    judgeQuestions.length < config.judgeCount
  ) {
    this.$message.warning('题库题目数量不足，无法组卷');
    return;
  }

  // ✅ 5. 构建试卷数据 —— 使用 userPaperId
  const questionTypeMap = { multiQuestion: 1, fillQuestion: 2, judgeQuestion: 3 };
  const paperData = [
    ...multiQuestions.slice(0, config.multipleCount).map(q => ({
      paperId: userPaperId,  // ✅ 使用唯一 userPaperId
      userId,
      questionType: questionTypeMap.multiQuestion,
      questionId: q.questionId
    })),
    ...fillQuestions.slice(0, config.fillCount).map(q => ({
      paperId: userPaperId,  // ✅
      userId,
      questionType: questionTypeMap.fillQuestion,
      questionId: q.questionId
    })),
    ...judgeQuestions.slice(0, config.judgeCount).map(q => ({
      paperId: userPaperId,  // ✅
      userId,
      questionType: questionTypeMap.judgeQuestion,
      questionId: q.questionId
    }))
  ];

  // ✅ 6. 清除旧题（现在安全了，因为每个 userPaperId 唯一）
  try {
    await this.$axios.delete('/api/paperManage/clear', {
      params: { paperId: userPaperId, userId }
    });
  } catch (e) {
    console.warn('清除旧题失败（可忽略）', e);
  }

  // ✅ 7. 插入新题
  const insertRes = await this.$axios.post('/api/paperManage/add', paperData);
  if (insertRes.data.code === 200) {
    this.$message.success('新试卷已生成，开始答题！');
  } else {
    this.$message.error(insertRes.data.message || '组卷失败');
    return;
  }

  // ✅ 8. 跳转时带上 userPaperId
  this.$router.push({
    path: '/examMsg',
    query: { examCode: exam.examCode, paperId: userPaperId,userId:userId }
  });

} catch (error) {
  console.error('进入考试失败:', error);
  this.$message.error('网络错误，请重试');
} finally {
  this.loading = false;
}

      // ✅ 跳转到答题页
      this.$router.push({
        path: '/examMsg',
        query: { examCode: exam.examCode }
      });
    },

    formatDateNow() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
    padding: 20px 0px 30px 0px;
    .el-pagination {
        display: flex;
        justify-content: center;
    }
}
.paper {
    h4 {
        cursor: pointer;
    }
}
.paper .item a {
    color: #000;
}
.wrapper .top .order {
    cursor: pointer;
}
.wrapper .top .order:hover {
    color: #0195ff;
    border-bottom: 2px solid #0195ff;
}
.wrapper .top .order:visited {
    color: #0195ff;
    border-bottom: 2px solid #0195ff;
}
.item .info i {
    margin-right: 5px;
    color: #0195ff;
}
.item .info span {
    margin-right: 14px;
}
.paper .item {
    width: 380px;
    border-radius: 4px;
    padding: 20px 30px;
    border: 1px solid #eee;
    box-shadow: 0 0 4px 2px rgba(217, 222, 234, 0.3);
    transition: all 0.6s ease;
}
.item {
  cursor: pointer;
}
.paper .item:hover {
    box-shadow: 0 0 4px 2px rgba(140, 193, 248, 0.45);
    transform: scale(1.03);
}
.paper .item .info {
    font-size: 14px;
    color: #88949b;
}
.paper .item .name {
    font-size: 14px;
    color: #88949b;
}
.paper * {
    margin: 20px 0;
}
.wrapper .paper {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
}
.top .el-icon-search {
    position: absolute;
    right: 10px;
    top: 10px;
}
.top .icon {
    position: relative;
}
.wrapper .top {
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
}
#myExam .search-li {
    margin-left: auto;
}
.top .search-li {
    margin-left: auto;
}
.top li {
    display: flex;
    align-items: center;
}
.top .search {
    margin-left: auto;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #eee;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}
.top .search:hover {
    color: #0195ff;
    border-color: #0195ff;
}
.wrapper .top {
    display: flex;
}
.wrapper .top li {
    margin: 20px;
}
#myExam {
    width: 980px;
    margin: 0 auto;
}
#myExam .title {
    margin: 20px;
}
#myExam .wrapper {
    background-color: #fff;
}
</style>